package com.hmyd.hmyd_android.shop;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.JfMallCollectionAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfo;
import com.hmyd.hmyd_android.dto.JfMallItemDto;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.ui.BasicActivity;
import com.hmyd.hmyd_android.view.PullToRefreshBase;
import com.hmyd.hmyd_android.view.PullToRefreshGridView;
import com.hmyd.hmyd_android.view.PullToRefreshBase.OnRefreshListener2;
import com.hmyd.hmyd_android.weigets.ILoadingLayout;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 积分商城，我的收藏
 * 
 * @author wangk
 *
 */
@ContentView(R.layout.activity_my_collect)
public class MyCollectActivity extends BasicActivity {

	private JfMallCollectionAdapter mallItemAdapter;

	private final int REFRESH_COLLECT = 1;
	private final int LOADMORE_COLLECT = 2;
	private final int DELETE_COLLECT = 3;

	private List<JfMallItemDto> mCollects = new ArrayList<JfMallItemDto>();
	private Page<JfMallItemDto> mCollectPage = new Page<JfMallItemDto>();

	@ViewInject(R.id.collectContent)
	private PullToRefreshGridView collectContent; // 收藏的商品
	@ViewInject(R.id.collectTitle)
	private View collectTitle; // 顶部标题
	@ViewInject(R.id.home_title_txt)
	private TextView home_title_txt;
	
	@ViewInject(R.id.home_right)
	private TextView home_right; // 右侧编辑按钮
	@ViewInject(R.id.optLayout)
	private RelativeLayout optLayout; // 底部操作布局
	
	private DtoInfo<JfMallItemDto> root; // 接收的数据

	@OnClick({R.id.optLayout })
	public void click(View view) {
		switch (view.getId()) {
		case R.id.optLayout:
			List<String> ids = mallItemAdapter.getIds();
			if (!Objects.equal(null, ids)) {
				for (String string : ids) {
					RequestParams parmas = new RequestParams();
					parmas.addBodyParameter("itemId", string);
					parmas.addBodyParameter("isCollection",
							String.valueOf(false));
					JfMallItemDto tempDto = null;
					for (JfMallItemDto dto : mCollects) {
						if (string.equals(dto.id)) {
							tempDto = dto;
						}
					}
					mCollects.remove(tempDto);
					onRequest(DELETE_COLLECT, UrlConstant.COLLECT,
							HttpMethod.POST, parmas);
				}
				mallItemAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		Type type = new TypeToken<DtoInfo<JfMallItemDto>>() {
		}.getType();
		switch (postId) {
		case REFRESH_COLLECT:
			root = gson.fromJson(msg, type);
			mCollectPage = root.data;
			mCollects.clear();
			mCollects = mCollectPage.records;
			mallItemAdapter.refreshData(mCollects);
			collectContent.onRefreshComplete();
			break;
		case LOADMORE_COLLECT:
			root= gson.fromJson(msg, type);
			mCollectPage = root.data;
			mCollects.addAll(mCollectPage.records);
			mallItemAdapter.refreshData(mCollects);
			collectContent.onRefreshComplete();
			break;
		case DELETE_COLLECT:
			onRequest(REFRESH_COLLECT, UrlConstant.COLLECTLIST,
					HttpMethod.GET, null);
			// TODO 删除收藏
			break;
		default:
			break;
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		collectContent.onRefreshComplete();
	}

	@Override
	protected void setParams() {
		home_title_txt.setText("我的收藏");
		home_right.setText("编辑");
		collectTitle.setOnTouchListener(touch);
		mCollects = Lists.newArrayList();
		mallItemAdapter = new JfMallCollectionAdapter(getApplicationContext(),
				mCollects);
		collectContent.setAdapter(mallItemAdapter);
		ILoadingLayout headLayout = collectContent.getLoadingLayoutProxy(true,
				false);
		headLayout.setPullLabel("下拉刷新");
		headLayout.setReleaseLabel("松开刷新");
		headLayout.setRefreshingLabel("加载中");

		ILoadingLayout endLabels = collectContent.getLoadingLayoutProxy(
				false, true);
		endLabels.setPullLabel("更多");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("加载中");// 刷新时
		endLabels.setReleaseLabel("松开可以加载更多");// 下来达到一定距离时，显示的提示

		/*
		 * 点击跳转事件监听
		 */
		collectContent.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent();
				intent.setClass(MyCollectActivity.this,
						GoodsDetailsActivity.class);
				intent.putExtra("id", mCollects.get(position).id);
				startActivity(intent);
			}
		});
		/*
		 * 下拉刷新，下拉加载
		 */
		collectContent.setOnRefreshListener(new OnRefreshListener2<GridView>() {

			@SuppressLint("SimpleDateFormat")
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				SimpleDateFormat myFmt = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String label = myFmt.format(new Date(System.currentTimeMillis()));
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				onRequest(REFRESH_COLLECT, UrlConstant.COLLECTLIST,
						HttpMethod.GET, null);
			}

			@SuppressLint("SimpleDateFormat")
			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				SimpleDateFormat myFmt = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String label = myFmt.format(new Date(System.currentTimeMillis()));
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				if(!root.data.hasMore) {
					collectContent.onRefreshComplete();
					return;
				}
				
				if (mCollects.size() > 0) {
					RequestParams params = new RequestParams();
					params.addBodyParameter(
							"lastCursor",
							String.valueOf(mCollects.get(mCollects.size() - 1).createdTime));
					onRequest(LOADMORE_COLLECT, UrlConstant.COLLECTLIST,
							HttpMethod.GET, params);
				} else {
					collectContent.onRefreshComplete();
				}
			}
		});
		onRequest(REFRESH_COLLECT, UrlConstant.COLLECTLIST, HttpMethod.GET,
				null);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		if (mallItemAdapter.checkShow) {
			home_right.setText("编辑");
			mallItemAdapter.checkShow = false;
			mallItemAdapter.notifyDataSetChanged();
			optLayout.setVisibility(View.GONE);
		} else {
			home_right.setText("取消");
			mallItemAdapter.checkShow = true;
			mallItemAdapter.notifyDataSetChanged();
			optLayout.setVisibility(View.VISIBLE);
		}
	}
}
